package com.joysuch.wwyt.patrol.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joysuch.wwyt.attendance.util.AttendanceDayUtils;
import com.joysuch.wwyt.common.constant.Constant;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.dataimport.service.DataImportService;
import com.joysuch.wwyt.mh.service.MhMonitoringTypeService;
import com.joysuch.wwyt.patrol.entity.PatrolCheckItem;
import com.joysuch.wwyt.patrol.entity.PatrolCheckPoint;
import com.joysuch.wwyt.patrol.entity.bean.*;
import com.joysuch.wwyt.patrol.entity.vo.*;
import com.joysuch.wwyt.patrol.enums.DataTypeEnum;
import com.joysuch.wwyt.patrol.mapper.PatrolCheckPointMapper;
import com.joysuch.wwyt.patrol.service.PatrolCheckItemService;
import com.joysuch.wwyt.patrol.service.PatrolCheckPointService;
import com.joysuch.wwyt.patrol.service.PatrolDataTypeService;
import com.joysuch.wwyt.risk.repository.RiskDistrictDao;
import com.joysuch.wwyt.risk.service.RiskEvaluationExcelImportService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

import static com.joysuch.wwyt.util.demo.ExcelUtilDemo.getRange;
import static com.joysuch.wwyt.util.demo.ExcelUtilDemo.setDataValidationFornum;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zr
 * @since 2022-02-28
 */
@Service
public class PatrolCheckPointServiceImpl extends ServiceImpl<PatrolCheckPointMapper, PatrolCheckPoint> implements PatrolCheckPointService {

    @Autowired
    private PatrolCheckPointMapper patrolCheckPointMapper;
    @Autowired
    private PatrolCheckItemService patrolCheckItemService;
    @Autowired
    private MhMonitoringTypeService mhMonitoringTypeService;
    @Autowired
    private PatrolDataTypeService patrolDataTypeService;
    @Autowired
    private RiskDistrictDao districtDao;
    @Autowired
    private RiskEvaluationExcelImportService riskEvaluationExcelImportService;

    @Lazy
    @Autowired
    private DataImportService dataImportService;

    @Override
    public List<CheckPlanDetailPointVo> findPlanPointByPlanId(Long planId) {
        Long tenentId = Context.getCurrentTenantId();
        String orgCode = Context.getCurrentOrgCode();
        return patrolCheckPointMapper.findPlanPointByPlanId(tenentId, orgCode, planId);
    }

    @Override
    public void saveCheckPoint(PatrolCheckPointBean patrolCheckPointBean) throws ApiBusinessException {
        //判断检查点名称是否重复
        Long tenentId = Context.getCurrentTenantId();
        String orgCode = Context.getCurrentOrgCode();
        Long count =  patrolCheckPointMapper.judgeForName(patrolCheckPointBean.getCheckPointName(),tenentId,orgCode);
        if (0 != count){
            throw new ApiBusinessException(Status.CHECK_POINT_NAME_REPEAT,patrolCheckPointBean.getCheckPointName());
        }
        PatrolCheckPoint checkPoint = new PatrolCheckPoint();
        checkPoint.setCheckPointName(patrolCheckPointBean.getCheckPointName());
        checkPoint.setCheckPointType(patrolCheckPointBean.getCheckPointType());
        checkPoint.setResponsibleDept(patrolCheckPointBean.getResponsibleDept());
        checkPoint.setBelongArea(patrolCheckPointBean.getBelongArea());
        checkPoint.setPositionMethod(patrolCheckPointBean.getPositionMethod());
        checkPoint.setLocation(patrolCheckPointBean.getLocation());
        checkPoint.setNfc(patrolCheckPointBean.getNfc());
        checkPoint.setStatus(patrolCheckPointBean.getStatus());
        checkPoint.setFinish(patrolCheckPointBean.getFinish());
        checkPoint.setMandatoryCheckIn(patrolCheckPointBean.getMandatoryCheckIn());
        //保存检查点基础信息
        patrolCheckPointMapper.insert(checkPoint);
        //保存检查项目
        List<PatrolCheckPointItemBean> itemBeanList = patrolCheckPointBean.getItemBeanList();
        saveForCheckItem(itemBeanList, checkPoint.getId());
    }

    /**
     * 将前端传入的检查项目信息转换保存到表中
     * @param itemBeanList
     * @return
     */
    private void saveForCheckItem(List<PatrolCheckPointItemBean> itemBeanList,Long pointId){
        List<PatrolCheckItem> checkItemList = new ArrayList<>();
        for (PatrolCheckPointItemBean bean : itemBeanList) {
            for (PatrolCheckPointItemDetailBean itemDetailBean : bean.getPatrolCheckPointItemDetailBeanList()) {
                PatrolCheckItem item = new PatrolCheckItem();
                item.setPointId(pointId);
                item.setDeviceId(bean.getDeviceId());
                item.setName(bean.getName());
                item.setCheckItem(itemDetailBean.getCheckItem());
                item.setCheckStandard(itemDetailBean.getCheckStandard());
                item.setDataType(itemDetailBean.getDataType());
                item.setDataTypeId(itemDetailBean.getDataTypeId());
                item.setSymbol(itemDetailBean.getSymbol());
                item.setNormalLeft(itemDetailBean.getNormalLeft());
                item.setNormalRight(itemDetailBean.getNormalRight());
                item.setNormalValueId(itemDetailBean.getNormalValueId());
                item.setPhotograph(itemDetailBean.getPhotograph());
                checkItemList.add(item);
            }
        }
        patrolCheckItemService.saveBatch(checkItemList);
    }

    @Override
    public ResultBean findListForPage(Integer page, Integer size, Long areaId , Long typeId , String pointName) {
        Page<CheckPointPageVo> pageVoPage = new Page<>(page ,size);
        Long tenentId = Context.getCurrentTenantId();
        String orgCode = Context.getCurrentOrgCode();
        //加权限,检查点目前不用加权限
        //Set<Long> authDepartIds = baseRoleDataAuthService.findAuthDepartIdsByCurUser();

        Page<CheckPointPageVo> resultPage = patrolCheckPointMapper.findListForPage(pageVoPage,areaId,tenentId,orgCode,typeId, pointName);
        List<CheckPointPageVo> checkPointPageVos = convertPointPage(resultPage.getRecords());
        return ResultBean.pageData(checkPointPageVos,resultPage.getTotal());
    }

    /**
     * 加入设备数量以及检查项目数量
     * @return
     */
    private List<CheckPointPageVo> convertPointPage(List<CheckPointPageVo> checkPointPageVoList){
        for (CheckPointPageVo checkPointPageVo : checkPointPageVoList) {
            if (StringUtils.isNotBlank(checkPointPageVo.getStatus())){
                checkPointPageVo.setStatusName(Constant.COMMON_SWITCH_ON.equals(checkPointPageVo.getStatus()) ? "启用" : "禁用");
            }
            //根据检查点查看一个检查点下有多少个项目
            Long checkItemNum = patrolCheckItemService.findCheckItemNumByPointId(checkPointPageVo.getId());
            checkPointPageVo.setCheckItemNum(checkItemNum);
            //根据检查点查看一个检查点下有多少个设备
            Long equipmentNum =  patrolCheckItemService.findEquipmentNumByPointId(checkPointPageVo.getId());
            checkPointPageVo.setEquipmentNum(equipmentNum);
        }
        return checkPointPageVoList;
    }

    @Override
    public CheckPointDetailVo getPointById(Long id) {
        //检查点的基本信息
        CheckPointDetailVo pointDetailVo = patrolCheckPointMapper.getPointById(id);
        //查出检查项目赋给vo
        List<CheckItemVo> checkItemVoList = patrolCheckItemService.getCheckItemByPointId(id);
        pointDetailVo.setCheckItemVoList(checkItemVoList);
        return pointDetailVo;
    }

    @Override
    public void updateCheckPoint(PatrolCheckPointBean bean) throws ApiBusinessException {
        //判断检查点名称除了自己是否重复
        Long tenentId = Context.getCurrentTenantId();
        String orgCode = Context.getCurrentOrgCode();
        Long count =  patrolCheckPointMapper.judgeForNameExcludeSelf(bean.getId(),bean.getCheckPointName(),tenentId,orgCode);
        if (0 != count){
            throw new ApiBusinessException(Status.CHECK_POINT_NAME_REPEAT,bean.getCheckPointName());
        }
        //先修改基础信息表
        PatrolCheckPoint point = new PatrolCheckPoint();
        point.setId(bean.getId());
        point.setCheckPointName(bean.getCheckPointName());
        point.setCheckPointType(bean.getCheckPointType());
        point.setResponsibleDept(bean.getResponsibleDept());
        point.setBelongArea(bean.getBelongArea());
        point.setPositionMethod(bean.getPositionMethod());
        point.setLocation(bean.getLocation());
        point.setNfc(bean.getNfc());
        point.setStatus(bean.getStatus());
        point.setFinish(bean.getFinish());
        point.setMandatoryCheckIn(bean.getMandatoryCheckIn());
        patrolCheckPointMapper.updateById(point);
        //删除项目
        List<Long> delItemIds = bean.getDelItemIds();
        List<Long> delDeviceIds = bean.getDelDeviceIds();
        if (CollectionUtil.isNotEmpty(delItemIds)){
            patrolCheckItemService.delByIds(delItemIds);
        }
        if (CollectionUtil.isNotEmpty(delDeviceIds)){
            patrolCheckItemService.delByDeviceIdsAndPointId(delDeviceIds,bean.getId());
        }
        //再修改检查项目表
        List<PatrolCheckPointItemBean> itemBeanList = bean.getItemBeanList();
        if (CollectionUtil.isNotEmpty(itemBeanList)){
            List<PatrolCheckItem> itemList = new ArrayList<>();
            for (PatrolCheckPointItemBean itemBean : itemBeanList) {
                List<PatrolCheckPointItemDetailBean> itemDetailBeanList = itemBean.getPatrolCheckPointItemDetailBeanList();
                for (PatrolCheckPointItemDetailBean itemDetailBean : itemDetailBeanList) {
                    PatrolCheckItem item = new PatrolCheckItem();
                    item.setId(itemDetailBean.getId());
                    item.setPointId(bean.getId());
                    item.setDeviceId(itemBean.getDeviceId());
                    item.setName(itemBean.getName());
                    item.setCheckItem(itemDetailBean.getCheckItem());
                    item.setCheckStandard(itemDetailBean.getCheckStandard());
                    item.setDataType(itemDetailBean.getDataType());
                    item.setDataTypeId(itemDetailBean.getDataTypeId());
                    item.setSymbol(itemDetailBean.getSymbol());
                    String left = itemDetailBean.getNormalLeft();
                    if (riskEvaluationExcelImportService.isNum(left)) {
                        left = riskEvaluationExcelImportService.getNumberString(left);
                        item.setNormalLeft(left);
                    }
                    String right = itemDetailBean.getNormalRight();
                    if (riskEvaluationExcelImportService.isNum(right)) {
                        right = riskEvaluationExcelImportService.getNumberString(right);
                        item.setNormalRight(right);
                    }
                    item.setNormalValueId(itemDetailBean.getNormalValueId());
                    item.setPhotograph(itemDetailBean.getPhotograph());
                    itemList.add(item);
                }
            }
            patrolCheckItemService.saveOrUpdateBatch(itemList);
        }

    }

    @Override
    public List<CheckPointListVo> getPointList() {
        Long tenentId = Context.getCurrentTenantId();
        String orgCode = Context.getCurrentOrgCode();
        List<CheckPointListVo> pointList = patrolCheckPointMapper.getPointList(tenentId, orgCode);
        for (CheckPointListVo checkPoint : pointList) {
            //根据检查点查看一个检查点下有多少个项目
            Long checkItemNum = patrolCheckItemService.findCheckItemNumByPointId(checkPoint.getId());
            checkPoint.setCheckItemNum(checkItemNum);
            //根据检查点查看一个检查点下有多少个设备
            Long equipmentNum =  patrolCheckItemService.findEquipmentNumByPointId(checkPoint.getId());
            checkPoint.setEquipmentNum(equipmentNum);
        }
        return pointList;
    }

    @Override
    public ResultBean deletePointById(Long id , Integer skipFlag){
        if (Integer.valueOf(0).equals(skipFlag)){
            List<String> planName = patrolCheckPointMapper.findBind(Context.getCurrentTenantId(), Context.getCurrentOrgCode(), id);
            if (CollectionUtil.isNotEmpty(planName)){
                String planNames = planName.stream().map(Object::toString).collect(Collectors.joining(Constant.SPLIT_COMMA));
                return ResultBean.success(String.format("该检查点已关联检查计划{%s},删除后将解除绑定,是否继续解除",planNames));
            }else {
                return ResultBean.success("是否确认删除?");
            }
        }
        //先将检查点删除
        patrolCheckPointMapper.deletePointById(id);
        //删除检查点和检查计划的关系,后续任务按照新配置去做
//        patrolPlanPointMappingService.deleteMappingByPointId(id);
        return ResultBean.defaultSuccessResult();
    }

    @Override
    public List<SimpleListDataType> getSimpleListDataType(String flag) {
        List<SimpleListDataType> result = new ArrayList<>();
        //数值
        if (DataTypeEnum.NUM.getValue().equals(flag)){
            result = mhMonitoringTypeService.getSimpleList();
        }else if (DataTypeEnum.STATE.getValue().equals(flag)){
            //状态,多级列表
            result = patrolDataTypeService.getSimpleList();
        }else if (DataTypeEnum.SHOCK.getValue().equals(flag)){
            result = patrolDataTypeService.getSimpleListShock();
        }
        return result;
    }

    @Override
    public CheckPointDetailVo getCheckPointByPointIdForApp(Long pointId) {
        //检查点的基本信息
        CheckPointDetailVo pointDetailVo = patrolCheckPointMapper.getPointById(pointId);
        //查出检查项目赋给vo
        List<CheckItemVo> checkItemVoList = patrolCheckItemService.getCheckItemByPointId(pointId);
        for (CheckItemVo checkItemVo : checkItemVoList) {
            // 有设备编号的拼上设备编号
            if (StringUtils.isNotBlank(checkItemVo.getDeviceCode())) {
                checkItemVo.setNameAndCode(checkItemVo.getDeviceName() + "[" + checkItemVo.getDeviceCode() +"]");
            }
            for (CheckItemDetailVo checkItemDetailVo : checkItemVo.getCheckItemDetailVoList()) {
                String dataType = checkItemDetailVo.getDataType();
                if (StringUtils.isNotBlank(dataType) && null != checkItemDetailVo.getDataTypeId() && DataTypeEnum.STATE.getValue().equals(dataType)){
                    List<String> options = patrolDataTypeService.findOptionByTypeId(checkItemDetailVo.getDataTypeId());
                    checkItemDetailVo.setOptions(options);
                }
            }
        }
        pointDetailVo.setCheckItemVoList(checkItemVoList);
        return pointDetailVo;
    }

    @Override
    public XSSFWorkbook exportCheckItemTem() {
        //创建工作簿对象
        XSSFWorkbook xssfWorkbook = null;
        FileInputStream fis =  null;
        InputStream inputStream = null;
        try {
            // 读取文件
            ClassPathResource classPathResource = new ClassPathResource("template" + File.separator + "检查点项目导入模板.xlsx");
            inputStream = classPathResource.getInputStream();
            xssfWorkbook = new XSSFWorkbook(inputStream);
            //获取工作簿下sheet的个数
            int sheetNum = xssfWorkbook.getNumberOfSheets();
            System.out.println("该excel文件中总共有："+sheetNum+"个sheet");
            //拿到模板的第一个sheet
            XSSFSheet dataSheet = xssfWorkbook.getSheetAt(0);
            //存放下拉列表的sheet
            XSSFSheet  hideSheet = xssfWorkbook.createSheet("dataLookup");
            //拿到数值数据类型
            List<SimpleListDataType> numList = mhMonitoringTypeService.getSimpleList();
            if (CollectionUtil.isNotEmpty(numList)){
                Object[] objects = numList.stream().map(SimpleListDataType::getDataTypeName).toArray();
                String[] numStrArr = Arrays.copyOf(objects, objects.length, String[].class);
                //第一行放置数据类型名称
                XSSFRow numRow = hideSheet.createRow(0);
                numRow.createCell(0).setCellValue("数值数据名称");
                for (int i = 0; i < numStrArr.length; i++) {
                    XSSFCell numCell = numRow.createCell(i + 1);
                    numCell.setCellValue(numStrArr[i]);
                }
                //下拉列表数据过多采用此方式
                setLongHSSFValidation(xssfWorkbook,numStrArr,dataSheet,2,500,8,3);
            }


            //拿到状态数据类型
            List<SimpleListDataType> stateList = patrolDataTypeService.getSimpleList();
            List<SimpleListDataType> stateListShock = patrolDataTypeService.getSimpleListShocks();

            if (CollectionUtil.isNotEmpty(stateListShock)){
                List<String> symbolList = dataImportService.getSymbolList();
                String[] symbolStr = symbolList.toArray(new String[symbolList.size()]);
                Object[] objects = stateListShock.stream().map(SimpleListDataType::getDataTypeName).toArray();
                String[] shockStrArr = Arrays.copyOf(objects, objects.length, String[].class);
                //第一行放置数据类型名称
                XSSFRow numRow = hideSheet.createRow(1);
                numRow.createCell(0).setCellValue("温振仪数据名称");
                for (int i = 0; i < shockStrArr.length; i++) {
                    XSSFCell numCell = numRow.createCell(i + 1);
                    numCell.setCellValue(shockStrArr[i]);
                }
                AttendanceDayUtils.createCells(dataSheet,shockStrArr,2,500,13,13);
                AttendanceDayUtils.createCells(dataSheet,symbolStr,2,500,14,14);
                //setLongHSSFValidation(xssfWorkbook,shockStrArr,dataSheet,2,500,12,4);
            }


            if (CollectionUtil.isNotEmpty(stateList)){
                Object[] objects = stateList.stream().map(SimpleListDataType::getDataTypeName).toArray();
                String[] stateStrArr = Arrays.copyOf(objects, objects.length, String[].class);
                Map<String,String[]> dateMap = new HashMap<String, String[]>();
                for (int i = 0; i < stateStrArr.length; i++) {
                    String dataTypeName = stateStrArr[i];
                    //因为之前做了去重，所以一个状态数据名称只会有一个,这里我们默认取第一个
                    List<SimpleListDataType> dataTypeList = stateList.stream().filter(e -> e.getDataTypeName().equals(dataTypeName)).collect(Collectors.toList());
                    SimpleListDataType dataType = dataTypeList.get(0);
                    if (Constant.COMMON_SWITCH_OFF.equals(dataType.getSingletonChoiceFlag()) && CollectionUtil.isNotEmpty(dataType.getOptionList())){
                        Object[] objects1 = dataType.getOptionList().stream().map(SimpleListOption::getOptionName).toArray();
                        String[] optionStrArr = Arrays.copyOf(objects1, objects1.length, String[].class);
                        dateMap.put(dataTypeName,optionStrArr);
                    }
                }
                //这一行作用是将此sheet隐藏，功能未完成时注释此行,可以查看隐藏sheet中信息是否正确
                xssfWorkbook.setSheetHidden(xssfWorkbook.getSheetIndex(hideSheet), false);
                int rowId = 2;
                // 设置第二行存入状态数据
                Row stateRow = hideSheet.createRow(rowId++);
                stateRow.createCell(0).setCellValue("状态数据名称");
                for(int i = 0; i < stateStrArr.length; i ++){
                    Cell stateCell = stateRow.createCell(i + 1);
                    stateCell.setCellValue(stateStrArr[i]);
                }
                Map<String, String> stateUUIDMap = new HashMap<>();
                for(int i = 0;i < stateStrArr.length;i++){
                    String key = stateStrArr[i];
                    String uuid = UUID.randomUUID().toString().replace("-","");
                    String[] son = dateMap.get(key);
                    if (null != son && son.length != 0){
                        Row row1 = hideSheet.createRow(rowId++);
                        row1.createCell(0).setCellValue(key);
                        for(int j = 0; j < son.length; j ++){
                            Cell cell0 = row1.createCell(j + 1);
                            cell0.setCellValue(son[j]);
                        }
                        // 添加名称管理器
                        String range = getRange(1, rowId, son.length);
                        Name name = xssfWorkbook.createName();
                        //key不可重复,且不能为数字
                       // name.setNameName("_" + key.replace("/","_"));
                        String regEx = "[\n`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？-]";
                        name.setNameName("_" + key.replaceAll(regEx,""));
                        String formula = "dataLookup!" + range;
                        name.setRefersToFormula(formula);
                    }
                }
                XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(dataSheet);
                // 一级规则
                DataValidationConstraint stateConstraint = dvHelper.createExplicitListConstraint(stateStrArr);
                // 四个参数分别是：起始行、终止行、起始列、终止列
                CellRangeAddressList stateRangeAddressList = new CellRangeAddressList(2, 202, 6, 6);
                DataValidation stateDataValidation = dvHelper.createValidation(stateConstraint, stateRangeAddressList);
                //验证
                stateDataValidation.createErrorBox("error", "请选择正确的状态名称");
                stateDataValidation.setShowErrorBox(true);
                stateDataValidation.setSuppressDropDownArrow(true);
                dataSheet.addValidationData(stateDataValidation);

                //对前200行设置有效性
                for(int i = 3;i < 204;i++){
                    setDataValidationFornum("G" ,dataSheet,i,8);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(fis);
            IOUtils.closeQuietly(inputStream);
        }
        return xssfWorkbook;
    }


    /**
     * 取到两个集合最大的size
     * @param excelItemList
     * @param numList
     * @return
     */
    private int judgeSize(List<ExcelItemBean> excelItemList , List<SimpleListDataType> numList){
        if (CollectionUtil.isEmpty(excelItemList)) {
            if (CollectionUtil.isEmpty(numList)){
                return 0;
            }else {
                return numList.size();
            }
        }else {
            if (CollectionUtil.isEmpty(numList)){
                return excelItemList.size();
            }else {
                return excelItemList.size() - numList.size() > 0 ? excelItemList.size() : numList.size() ;
            }
        }
    }


    private void createCells(XSSFRow row, String[] titleTexts, boolean isTitle, XSSFWorkbook workbook,int index) {
        for (String text : titleTexts) {
            XSSFCell c = row.createCell(index++);
            c.setCellStyle(isTitle ? title(workbook, false) : text(workbook));
            c.setCellValue(text);
            row.getSheet().setColumnWidth(index - 1, 20 * 256);
        }
    }

    //小标题的样式
    public CellStyle title(Workbook wb, Boolean isRed) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short) 12);
        if (isRed) {
            font.setColor((short) 2);
        }
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);                //横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);     //纵向居中
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short) 10);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.LEFT);              //横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);     //纵向居中
        return style;
    }

    @Override
    public XSSFWorkbook exportCheckItemData(Long pointId) {
        //根据pointId获取检查点下的检查项目数据
        List<CheckItemDetailVo> reultData = patrolCheckItemService.getPointCheckItemData(pointId);
        //拿到模板和动态下拉列表,开始拼接数据
        XSSFWorkbook workbook = exportCheckItemTem();
        splicings(reultData,workbook);
        return workbook;
    }

    private void splicings(List<CheckItemDetailVo> reultData,XSSFWorkbook workbook) {
        if (CollectionUtil.isNotEmpty(reultData) && null != workbook) {
            for (int i = 0; i < reultData.size(); i++) {
                XSSFSheet sheet = workbook.getSheetAt(0);
                XSSFRow r = sheet.createRow(i + 2);
                String checkObj = "";
                if (reultData.get(i).getDeviceId() < 0) {
                    checkObj = reultData.get(i).getDeviceName();
                }
                createCells(r, new String[]{reultData.get(i).getDeviceCode(), "", ""}, false, workbook, 0);
                createCells(r, new String[]{reultData.get(i).getDeviceTypeName(), "", ""}, false, workbook, 1);
                createCells(r, new String[]{checkObj, "", ""}, false, workbook, 2);
                createCells(r, new String[]{reultData.get(i).getCheckItem(), "", ""}, false, workbook, 3);
                createCells(r, new String[]{reultData.get(i).getCheckStandard(), "", ""}, false, workbook, 4);
                if (Constant.COMMON_SWITCH_OFF.equals(reultData.get(i).getPhotograph())) {
                    createCells(r, new String[]{"否", "", ""}, false, workbook, 5);
                } else {
                    createCells(r, new String[]{"是", "", ""}, false, workbook, 5);
                }
                DataTypeEnum dataTypeEnum = DataTypeEnum.find(reultData.get(i).getDataType());
                switch (dataTypeEnum) {
                    case STATE:
                        createCells(r, new String[]{reultData.get(i).getDataTypeName(), "", ""}, false, workbook, 6);
                        if (Constant.COMMON_SWITCH_OFF.equals(reultData.get(i).getSingletonChoiceFlag())) {
                            createCells(r, new String[]{reultData.get(i).getNormalValueName(), "", ""}, false, workbook, 7);
                        }
                        break;
                    case NUM:
                        createCells(r, new String[]{reultData.get(i).getDataTypeName(), "", ""}, false, workbook, 8);
                        createCells(r, new String[]{reultData.get(i).getSymbol(), "", ""}, false, workbook, 9);
                        if (">".equals(reultData.get(i).getSymbol())
                                || "≥".equals(reultData.get(i).getSymbol())
                                || "<".equals(reultData.get(i).getSymbol())
                                || "≤".equals(reultData.get(i).getSymbol())) {
                            createCells(r, new String[]{reultData.get(i).getNormalLeft(), "", ""}, false, workbook, 10);
                        } else if ("><".equals(reultData.get(i).getSymbol())
                                || "≥≤".equals(reultData.get(i).getSymbol())) {
                            createCells(r, new String[]{reultData.get(i).getNormalLeft(), "", ""}, false, workbook, 10);
                            createCells(r, new String[]{reultData.get(i).getNormalRight(), "", ""}, false, workbook, 11);
                        }

                        break;
                    case TEXT:
                        createCells(r, new String[]{"文本", "", ""}, false, workbook, 12);
                        break;
                    case SHOCK:
                        if ("振动".equals(reultData.get(i).getDataTypeName())) {
                            createCells(r, new String[]{reultData.get(i).getDataTypeName(), "", ""}, false, workbook, 13);
                        } else {
                            createCells(r, new String[]{reultData.get(i).getDataTypeName(), "", ""}, false, workbook, 13);
                            createCells(r, new String[]{reultData.get(i).getSymbol(), "", ""}, false, workbook, 14);
                            if (">".equals(reultData.get(i).getSymbol())
                                    || "≥".equals(reultData.get(i).getSymbol())
                                    || "<".equals(reultData.get(i).getSymbol())
                                    || "≤".equals(reultData.get(i).getSymbol())) {
                                createCells(r, new String[]{reultData.get(i).getNormalLeft(), "", ""}, false, workbook, 15);
                            } else if ("><".equals(reultData.get(i).getSymbol())
                                    || "≥≤".equals(reultData.get(i).getSymbol())) {
                                createCells(r, new String[]{reultData.get(i).getNormalLeft(), "", ""}, false, workbook, 15);
                                createCells(r, new String[]{reultData.get(i).getNormalRight(), "", ""}, false, workbook, 16);
                            }
                            break;
                        }
                }
            }
        }
    }

    @Override
    public String findNameById(Long pointId) {
        return patrolCheckPointMapper.findNameById(pointId,Context.getCurrentTenantId(),Context.getCurrentOrgCode());
    }

    public String getLocationById(Long id) {
        String location = null;
        PatrolCheckPoint point = patrolCheckPointMapper.selectLocationById(id);
        location = point.getLocation();
        // 点位无位置信息则取所在区域的位置
        if (StringUtils.isBlank(location)) {
            location = districtDao.findLocationById(point.getBelongArea());
        }
        return location;
    }

    /**
     *  解决下拉框过长不显示问题
     * @param xssfWorkbook
     * @param deptList 下拉数据数组
     * @param sheet
     * @param firstRow 开始行
     * @param endRow 结束行
     * @param cellNum 下拉框所在的列
     * @param sheetIndex
     */
    private void setLongHSSFValidation(XSSFWorkbook xssfWorkbook,String[] deptList ,XSSFSheet sheet,int firstRow, int endRow, int cellNum,int sheetIndex){
        String hiddenName = "numData" + cellNum;
        Name category1Name = xssfWorkbook.createName();
        category1Name.setNameName(hiddenName);
        //拿到sheet中数据的范围
        String range = getRange(1, 1, deptList.length);
        category1Name.setRefersToFormula("dataLookup!" + range);
        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = helper.createFormulaListConstraint(hiddenName);
        CellRangeAddressList addressList = new CellRangeAddressList(firstRow, endRow, cellNum, cellNum);
        DataValidation dataValidation = helper.createValidation(constraint, addressList);
        if (dataValidation instanceof XSSFDataValidation) {
            // 数据校验
            dataValidation.createErrorBox("error","请选择正确的数值数据");
            dataValidation.setSuppressDropDownArrow(true);
            dataValidation.setShowErrorBox(true);
        } else {
            dataValidation.setSuppressDropDownArrow(false);
        }
        // 作用在目标sheet上
        sheet.addValidationData(dataValidation);
    }
}
